﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Security.Principal;

using iTextSharp.text.pdf;
using PdfSharp.Drawing;

namespace iPdf
{

    public static class Helper
    {
        #region Fields
        //the Windows Live Messenger style taskbar notifier
        static WlmStyleTaskbarNotifier wlmStyleNotifier ;
        #endregion

        #region Properties
        public static string MyDocumentsDir
        {
            get
            {
                return RegularizeDirectory(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            }
        }

        public static string MyPicturesDir
        {
            get
            {
                return RegularizeDirectory(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
            }
        }

        public static string RoamingDir
        {
            get
            {
                string roamingDir = Path.Combine( Environment.GetFolderPath(
                    Environment.SpecialFolder.ApplicationData) , Global.Tata + @"\");
                if(!Directory.Exists(roamingDir))
                {
                    Directory.CreateDirectory(roamingDir);
                }

                return roamingDir;
            }
        }

        public static string TemporaryDir
        {
            get
            {
                return Path.GetTempPath();
            }
        }

        public static string WindowsDir
        {
            get
            {
                return GetSpecialFolderPath(IntPtr.Zero, ShellSpecialFolders.WINDOWS);
            }
        }

        public static string SystemFontsDir
        {
            get
            {
                return GetSpecialFolderPath(IntPtr.Zero, ShellSpecialFolders.FONTS);
            }
        }

        public static string ProgramFilesDir
        {
            get
            {
                return GetSpecialFolderPath(IntPtr.Zero, ShellSpecialFolders.PROGRAM_FILES);
            }
        }

        public static string BuiltInImagesDir
        {
            get
            {
                string builtInImagesDir = Helper.RoamingDir + "BuiltInImages\\";
                if (!Directory.Exists(builtInImagesDir))
                {
                    Directory.CreateDirectory(builtInImagesDir);
                }

                return builtInImagesDir;
            }
        }

        public static string RecentStampImagesDir
        {
            get
            {
                string recentStampImagesDir = Helper.RoamingDir + "RecentStampImages\\";
                if (!Directory.Exists(recentStampImagesDir))
                {
                    Directory.CreateDirectory(recentStampImagesDir);
                }

                return recentStampImagesDir;
            }
        }

        public static string RecentWatermarkImagesDir
        {
            get
            {
                string recentWatermarkImagesDir = Helper.RoamingDir + "RecentWatermarkImages\\";
                if (!Directory.Exists(recentWatermarkImagesDir))
                {
                    Directory.CreateDirectory(recentWatermarkImagesDir);
                }

                return recentWatermarkImagesDir;
            }
        } 

        #endregion

        #region Constants
        public const string NewLine = "\r\n";

        public const string Space = " ";

        public const string Underline = "_";

        public const string Tab = "\t";

        public const string Ampersand = "&";

        public const string Semicolon = ";";
        public const char SemicolonChar = ';';
        public const string Dot = ".";
        public const string Asterisk = "*";
        public const string Slash = "/";
        public const string Colon = ":";
        #endregion

        #region Statics
        public static string GetChinaStyleIndexNo(int index)
        {
            const int maxIndexNumber = 9;
            const int minIndexNumber = 1;
            if (index < minIndexNumber ||
                index > maxIndexNumber)
            {
                return string.Empty;
            }
            char no1 = '❶';
            return string.Empty + (char)(no1 + (index - 1));
        }

        public static void EnableControl(System.Windows.Forms.Control controlContainer,
                                                        bool enabled)
        {
            EnableControl(controlContainer, enabled, true);
        }

        public static void EnableControl(System.Windows.Forms.Control controlContainer,
                                                        bool enabled, bool includeSelf)
        {
            foreach (System.Windows.Forms.Control control in controlContainer.Controls)
            {
                EnableControl(control, enabled, true);
            }

            if (enabled)
            {
                Control parent = controlContainer.Parent;
                Stack<Control> ancestors = new Stack<Control>();
                while (parent != null && parent.Enabled == false)
                {
                    ancestors.Push(parent);
                    parent = parent.Parent;
                }

                while (ancestors.Count > 0)
                {
                    Control ancester = ancestors.Pop();
                    ancester.Enabled = true;
                }
            }

            if (includeSelf)
            {
                controlContainer.Enabled = enabled;
            }
        }

        public static string RemoveFileExt(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return null;
            }

            try
            {
                string ext = Path.GetExtension(fileName);
                if (string.IsNullOrEmpty(ext))
                {
                    return null;
                }
                return fileName.Substring(0, fileName.Length - ext.Length);
            }
            catch
            {
                return null;
            }
        }


        public static bool IsFileInUse(string file)
        {
            bool isInUse = false;
            //always use a try...catch to deal 
            //with any exceptions that may occur
            try
            {
                //check if the file exists, if it 
                //doesnt exist raise an error
                if (!File.Exists(file))
                {
                    throw new FileNotFoundException(file + " could not be found!");
                }
                else
                {
                    RandomAccessFileOrArray stream = new RandomAccessFileOrArray(file);
                    stream.Close();
                }
            }
            catch
            {
                isInUse = true;
            }
            return isInUse;
        }

        public static bool IsAscii(string str)
        {
            return UnicodeToAscii(str) == str;
        }

        public static string UnicodeToAscii(string uniStr)
        {
            Encoding asciiEncoding = Encoding.ASCII;
            byte[] bytes = asciiEncoding.GetBytes(uniStr);
            string asciiStr = string.Empty;
            char subChar = '_';
            foreach (char uniChar in uniStr)
            {
                if (uniChar >= 0 && uniChar <= 0x7F)
                {
                    asciiStr += uniChar;
                }
                else
                {
                    asciiStr += subChar;
                }
            }

            return asciiStr;
        }

        public static string RegularizeDirectory(string path)
        {
            if (!string.IsNullOrEmpty(path) && !path.EndsWith(@"\"))
            {
                path += '\\';
            }

            return path;
        }

        public static string AddParenthesisesToString(string str)
        {
            return "【" + str + "】";
        }

        public static string GenerateGuid()
        {
            return Guid.NewGuid().ToString();
        }

        public static string GetTemporaryFile(string ext)
        {
            string tmpFileName = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(ext))
                {
                    ext = string.Empty;
                }
                else
                {
                    if (!ext.StartsWith(Helper.Dot))
                        ext = Helper.Dot + ext;
                }

                tmpFileName = TemporaryDir + GenerateGuid() + ext;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return tmpFileName;
        }


        public static bool StartFile(string fileName)
        {
            try
            {
                if (File.Exists(fileName) && !Helper.IsFileInUse(fileName))
                {
                    //open destination file
                    System.Diagnostics.Process.Start(fileName);
                    return true;
                }
            }
            catch
            {
                return false;
            }

            return false;
        }

        public static void OpenFileLocation(string path)
        {
            string argument = "/select, " + path;
            System.Diagnostics.Process.Start("Explorer.exe", argument);
        }

        public static void OpenDirectory(string dir)
        {
            if (Directory.Exists(dir))
            {
                System.Diagnostics.Process.Start("Explorer.exe", Helper.QuoteString(dir));
            }
        }

        public static void CollectGarbage()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        public static string GenerateErrorReport(string errorMsg)
        {
            return GenerateErrorReport(errorMsg, "Unknown", "Contact our support team");
        }

        public static string GenerateErrorReport(string errorMsg, string cause)
        {
            return GenerateErrorReport(errorMsg, cause, "Contact our support team");
        }

        public static string GenerateErrorReport(string errorMsg, string cause, string solution)
        {
            if (string.IsNullOrEmpty(cause))
            {
                cause = "Unknown";
            }

            if (string.IsNullOrEmpty(solution))
            {
                solution = "Unknown";
            }

            return "Error: " + errorMsg + Global.Newline +
                       "Cause: " + cause + Global.Newline +
                       "Solution: " + solution;
        }

        public static FileStatus CheckFileStatus(string fileName)
        {
            return File.Exists(fileName) ?
                ( IsFileInUse(fileName)? FileStatus.InUse : FileStatus.Normal ) : 
                FileStatus.NotExist;
        }

        public static bool CheckExistsAndAccessible(string fileName)
        {
            if (CheckFileStatus(fileName) != FileStatus.Normal) 
            {
                return false;
            }

            return true;
        }

        public static FileStream OpenWrite(string path)
        {
            return new FileStream(path, FileMode.Create);
        }

        public static void DeleteFile(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        public static void VerifyFile(string source)
        {
            VerifyItem(source, null);
        }

        public static void VerifyItem(string source, string destination)
        {
            if (source == destination)
            {
                throw new TataException("The source file can't be the same with the destionation file");
            }

            if (!CheckExistsAndAccessible(source))
            {
                throw new TataException("Can't access the file " + source);
            }

            if (!string.IsNullOrEmpty(destination))
            {
                Helper.DeleteFile(destination);
            }
        }

        public static void Sleep(int seconds)
        {
            System.Threading.Thread.Sleep(seconds * 1000);
        }

        public static XmlDocument CreateXmlDocument()
        {
            XmlDocument xmlDoc = new  XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(xmlDeclaration);
            return xmlDoc;
        }

        public static OpenFileDialog CreateOpenFileDialog(FileFormat format, bool multiSelect)
        {
            return CreateOpenFileDialog(new FileFormat[] { format }, multiSelect);
        }

        public static OpenFileDialog CreateOpenFileDialog(FileFormat[] formats, bool multiSelect)
        {
            OpenFileDialog fileOpen = new OpenFileDialog();
            fileOpen.AutoUpgradeEnabled = true;
            fileOpen.CheckFileExists = true;
            fileOpen.CheckPathExists = true;
            fileOpen.Multiselect = multiSelect;

            string filter = string.Empty;
            string separator = "|";
            foreach (FileFormat format in formats)
            {
                filter += format.FilterString + separator;
                Collection<FileFormat> subFormats = format.SubFormats;
                if (subFormats.Count > 1)
                {
                    foreach (FileFormat subFormat in subFormats)
                    {
                        filter += subFormat.FilterString + separator;
                    }
                }
            }
            //remove the last separator
            if (filter.Length > 0 && filter.EndsWith(separator))
            {
                filter = filter.Substring(0, filter.Length - 1);
            }
            fileOpen.Filter = filter;

            return fileOpen;
        }

        public static SaveFileDialog CreateSaveFileDialog(FileFormat format, string defaultFileName)
        {
            return CreateSaveFileDialog(new FileFormat[] { format }, defaultFileName);
        }

        public static SaveFileDialog CreateSaveFileDialog(FileFormat[] formats, string defaultFileName)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Where do you want to save file?";
            saveFileDialog.FileName = defaultFileName;
            saveFileDialog.AddExtension = true;
            saveFileDialog.RestoreDirectory = true;

            string filter = string.Empty;
            string separator = "|";
            foreach (FileFormat format in formats)
            {
                filter += format.FilterString + separator;
            }
            //remove the last separator
            if (filter.Length > 0 && filter.EndsWith(separator))
            {
                filter = filter.Substring(0, filter.Length - 1);
            }

            saveFileDialog.Filter = filter;

            return saveFileDialog;
        }

        public static string QuoteString(string str)
        {
            if (str != null)
            {
                str = "\"" + str + "\"";
            }

            return str;
        }

        public static void CopyFile(string src, string dest)
        {
            DeleteFile(dest);

            //wait until the file is deleted
            while (File.Exists(dest))
            {
            }

            File.Copy(src, dest);
        }

        public static void MoveFile(string src, string dest)
        {
            if (File.Exists(dest)) 
            {
                DeleteFile(dest);
            }
            File.Move(src, dest);
        }

        /// <summary>
        /// Analyze the arguments to extract the task
        /// </summary>
        /// <param name="args">The arguments to be analyzed</param>
        /// <returns></returns>
        public static Task AnalyzeArguments(string[] args)
        {
            if (args.Length < 2)
            {
                return null;
            }

            string page = args[0];
            string[] files = new string[args.Length - 1];
            Array.ConstrainedCopy(args, 1, files, 0, files.Length);
            return new Task(page, files);
        }

        /// <summary>
        /// Convert bool? to CheckState
        /// </summary>
        /// <param name="isChecked">The bool? variable</param>
        /// <returns></returns>
        public static CheckState NullableBoolToCheckState(bool? isChecked)
        {
            CheckState checkState;
            if (isChecked == true)
            {
                checkState = CheckState.Checked;
            }
            else if (isChecked == false)
            {
                checkState = CheckState.Unchecked;
            }
            else
            {
                checkState = CheckState.Indeterminate;
            }

            return checkState;
        }

        public static CheckState BoolToCheckState(bool isChecked)
        {
            if (isChecked == true)
            {
                return CheckState.Checked;
            }
            else
            {
                return CheckState.Unchecked;
            }
        }

        /// <summary>
        /// Convert CheckState to bool?
        /// </summary>
        /// <param name="checkState">The CheckState variable</param>
        /// <returns></returns>
        public static bool? CheckStateToNullableBool(CheckState checkState)
        {
            bool? isChecked ;
            if (checkState == CheckState.Checked)
            {
                isChecked = true;
            }
            else if (checkState == CheckState.Unchecked)
            {
                isChecked = false;
            }
            else
            {
                isChecked = null;
            }

            return isChecked;
        }

        public static bool IsProgramRunning(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            return processes.Length > 0;
        }

        public static void SendAsEmail(string fileName)
        {
            MAPI mapi = new MAPI();
            mapi.AddAttachment(fileName);
            mapi.SendMailPopup("A document", "");
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Single.ToString")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Single.ToString")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Single.ToString")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")]
        public static string GetFileSizeString(int length)
        {
            string fileSize = string.Empty;

            int digits = 2;
            int kb = 1024;
            int mb = 1024 * kb;
            int gb = 1024 * mb;

            float gbCount =  (float)length / (float) gb;
            if (gbCount > 1.0f)
            {
                fileSize += Helper.RoundFloat(gbCount, digits).ToString() + " GB";
                return fileSize;
            }

            float mbCount = (float)length / (float)mb;
            if (mbCount > 1.0f)
            {
                fileSize += Helper.RoundFloat(mbCount, digits).ToString() + " MB";
                return fileSize;
            }

            float kbCount = (float)length / (float)kb;
            if (kbCount > 1.0f)
            {
                fileSize += Helper.RoundFloat(kbCount, digits).ToString() + " KB";
                return fileSize;
            }

            fileSize += length.ToString() + " Bytes";
            return fileSize;
        }

        public static string GetDirectoryName(string path)
        {
            return RegularizeDirectory(Path.GetDirectoryName(path));
        }

        public static bool IsValidFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return false;
            }

            try
            {
                FileInfo info = new FileInfo(fileName);
                if (info == null || info.Directory == null ||
                    string.IsNullOrEmpty( info.Name ))
                {
                    return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static ToolTip CreateToolTip()
        {
            return CreateToolTip(null);
        }

        public static ToolTip CreateToolTip(IContainer container)
        {
            ToolTip toolTip = container == null? new ToolTip() : new ToolTip(container);
            toolTip.ToolTipIcon = ToolTipIcon.Info;
            toolTip.UseFading = true;

            return toolTip;
        }

        public static bool ParseBool(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }

            try
            {
                return bool.Parse(value);
            }
            catch
            {
                return false;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.Parse(System.String)")]
        public static int? ParseInt(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }

            try
            {
                return int.Parse(value);
            }
            catch
            {
                return null;
            }
        }

        public static FileInfo[] FindFilesInDirectory(string dir, FileFormat fmt)
        {
            if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
            {
                throw new ArgumentException("Invalid directory specified");
            }
            Collection<string> wildcards = new Collection<string>();

            if (fmt == null)
            {
                wildcards.Add("*.*");
            }
            else
            {
                wildcards = fmt.Wildcards;
            }

            List<FileInfo> files = new List<FileInfo>();
            DirectoryInfo dirInfo = new DirectoryInfo(dir);

            foreach (string wildcard in wildcards)
            {
                files.AddRange( dirInfo.GetFiles(wildcard ) );
            }

            return files.ToArray();
        }

        public static double RadiansToDegrees(double radians)
        {
            return radians * (180 / Math.PI);
        }

        public static double DegreesToRadians(double degrees)
        {
            return degrees * (Math.PI / 180);
        }

        public static void AdjustSizeAndLocationByOffset(System.Windows.Forms.Control control, int horizontalLocationOffset, int widthOffset,
                                                                            int verticalLocationOffset, int heightOffset)
        {
            if (control == null)
            {
                return;
            }

            control.SuspendLayout();

            control.Location = new Point(control.Left + horizontalLocationOffset, control.Top + verticalLocationOffset);
            control.Size = new Size(control.Size.Width + widthOffset, control.Size.Height + heightOffset);

            control.ResumeLayout(true);
        }

        public static void ShrinkLeft(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, -offset, 0, 0);
        }

        public static void ShrinkRight(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, offset, -offset, 0, 0);
        }

        public static void ShrinkUp(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, 0, 0, -offset);
        }

        public static void ShrinkDown(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, 0, offset, -offset);
        }

        public static void StretchLeft(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, -offset, offset, 0, 0);
        }

        public static void StretchRight(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, offset, 0, 0);
        }

        public static void StretchUp(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, 0, -offset, offset);
        }

        public static void StretchDown(System.Windows.Forms.Control control, int offset)
        {
            AdjustSizeAndLocationByOffset(control, 0, 0, 0, offset);
        }

        public static void ShowTooltipAt(  string title, string text, 
                                                            ToolTipIcon icon, bool isBalloon,
                                                            IWin32Window window, 
                                                            Point location, int duration)
        {
            ToolTip tooltip = new ToolTip();
            tooltip.ToolTipTitle = title;
            tooltip.ToolTipIcon = icon;
            tooltip.IsBalloon = isBalloon;

            tooltip.Show(text, window, location, duration);
        }

        public static bool IsNumeric(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;

            foreach (char c in str)
            {
                if (!Char.IsNumber(c))
                {
                    return false;
                }
            }
            return true;
        }

        public static void ShowNotification(string title, string text)
        {
            if (wlmStyleNotifier == null)
            {
                wlmStyleNotifier = new WlmStyleTaskbarNotifier();
            }
            wlmStyleNotifier.ShowNotification(title, text);
        }

        public static void ShowNotification(string title, string text, bool contentAsLink)
        {
            if (wlmStyleNotifier == null)
            {
                wlmStyleNotifier = new WlmStyleTaskbarNotifier();
            }
            wlmStyleNotifier.ShowNotification(title, text, contentAsLink);
        }

        public static string ShowSaveFileDialog(FileFormat format)
        {
            return Global.MainWindow.ShowSaveFileDialog(new FileFormat[] { format }, null);
        }

        public static string ShowSaveFileDialog(FileFormat format, string defaultFileName)
        {
            return Global.MainWindow.ShowSaveFileDialog(new FileFormat[] { format }, defaultFileName);
        }

        public static string ShowChooseDirectoryDialog()
        {
            return Global.MainWindow.ShowChooseDirectoryDialog();
        }

        public static string SaveFile(FileFormat[] formats, string defaultFileName)
        {
            SaveFileDialog saveFileDlg = Helper.CreateSaveFileDialog(formats, defaultFileName);

            if (saveFileDlg.ShowDialog() == DialogResult.OK)
            {
                Global.RecentFiles.Add(saveFileDlg.FileName);
                return saveFileDlg.FileName;
            }

            return null;
        }

        public static string ChooseDirectory()
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.ShowNewFolderButton = true;
            folderBrowser.SelectedPath = Global.MainWindow.DefaultOutputFolder;

            return folderBrowser.ShowDialog() == DialogResult.OK?
                        folderBrowser.SelectedPath : null;
        }

        public static string GetImageInfo(Image img)
        {
            string imageInfo = string.Empty;
            imageInfo += img.Size.ToString();
            return imageInfo;
        }

        public static byte[] LittleEndianBytesOfDWord(uint dword)
        {
            byte[] bytes = new byte[Global.SizeOfDWordInBytes];

            ushort lowWord = GetLowWord(dword);
            ushort highWord = GetHighWord(dword);
            bytes[0] = GetLowByte(lowWord);
            bytes[1] = GetHighByte(lowWord);
            bytes[2] = GetLowByte(highWord);
            bytes[3] = GetHighByte(highWord);

            return bytes;
        }

        public static ushort GetHighWord(uint dword)
        {
            return (ushort)( dword >> (Global.SizeOfDwordInBits / 2) );
        }

        public static ushort GetLowWord(uint dword)
        {
            return (ushort)(dword & 0x0000FFFFU);
        }

        public static byte GetHighByte(ushort word)
        {
            return (byte)(word >> (Global.SizeOfWordInBits / 2));
        }

        public static byte GetLowByte(ushort word)
        {
            return (byte)(word & 0x00FFU);
        }

        /// <summary>
        /// Get the path of those special folders
        /// </summary>
        public static string GetSpecialFolderPath(IntPtr hwnd, ShellSpecialFolders nFolder)
        {
            StringBuilder sb = new StringBuilder(WinApi.MAX_PATH);
            WinApi.SHGetSpecialFolderPath(hwnd, sb, nFolder, false);
            return sb.ToString();
        }

        public static bool IsUserAnAdmin()
        {
            WindowsIdentity wid = WindowsIdentity.GetCurrent();
            WindowsPrincipal wp = new WindowsPrincipal(wid);
            return wp.IsInRole(WindowsBuiltInRole.Administrator);
        }

        public static XFontStyle GetAvailableFontStyle(FontFamily fontFamily)
        {
            if (fontFamily.IsStyleAvailable(FontStyle.Regular))
            {
                return XFontStyle.Regular;
            }

            if (fontFamily.IsStyleAvailable(FontStyle.Bold))
            {
                return XFontStyle.Bold;
            }

            if (fontFamily.IsStyleAvailable(FontStyle.Italic))
            {
                return XFontStyle.Italic;
            }

            if (fontFamily.IsStyleAvailable(FontStyle.Strikeout))
            {
                return XFontStyle.Strikeout;
            }

            if (fontFamily.IsStyleAvailable(FontStyle.Underline))
            {
                return XFontStyle.Underline;
            }

            throw new ArgumentException();
        }

        public static XMatrix PdfPageSpaceToWorldSpace(SizeF pageSize)
        {
            XMatrix transformer = new Matrix();
            transformer.TranslatePrepend(0, pageSize.Height);
            transformer.ScalePrepend(1, -1);
            return transformer;
        }

        public static string ByteToHexString(byte b)
        {
            return string.Format("{0, 2:X}", b).Replace(Space, "0");
        }

        public static byte HexStringToByte(string byteStr)
        {
            return byte.Parse(byteStr, System.Globalization.NumberStyles.HexNumber);
        }

        public static string XColorToString(XColor color)
        {
            string colorString = "#";

            colorString += ByteToHexString(color.R);
            colorString += ByteToHexString(color.G);
            colorString += ByteToHexString(color.B);

            return colorString;
        }

        public static XColor StringToXColor(string colorString)
        {
            XColor color = new XColor();
            color.A = 1.0;

            int index = 1;
            int len = 2;
            string redComponent = colorString.Substring(index, len);
            color.R = HexStringToByte(redComponent);

            index += len;
            string greenComponent = colorString.Substring(index, len);
            color.G = HexStringToByte(greenComponent);

            index += len;
            string blueComponent = colorString.Substring(index, len);
            color.B = HexStringToByte(blueComponent);

            return color;
        }

        public static bool IsColorString(string colorString)
        {
            if (string.IsNullOrEmpty(colorString) ||
                colorString.Length != 7 ||
                !colorString.StartsWith("#"))
            {
                return false;
            }

            string colorValue = colorString.Substring(1);
            try
            {
                Int32.Parse(colorValue, System.Globalization.NumberStyles.HexNumber);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static float RoundFloat(float f, int digits)
        {
            return (float)Math.Round(f, digits);
        }

        public static void ShowError(TataException exception)
        {
            MessageBox.Show(exception.ToString(), "Error", MessageBoxButtons.OK);
        }
        #endregion
    }




}
